﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Table = FCNS.Data.Table;
using DoubleH.Utility;
using System.Windows.Interop;
using System.Collections;
using DoubleH.Utility.Configuration;
using System.Collections.ObjectModel;
using System.Diagnostics;

namespace POS.Templete.BarTemplete
{
    /// <summary>
    /// StoreSales.xaml 的交互逻辑
    /// </summary>
    public partial class PageSale : Page, ISaleTemplete
    {
        private enum EnumMode
        {
            NULL,
            数量,
            价格,
            会员
        }

        public PageSale()
        {
            InitializeComponent();
        }

        public event dSaleToPayEvent Saled;
        public event dZengSong ZengSong;
        public event dEditProduct EditProduct;
        public event dNoParams JiaoBan;
        EnumMode mode = EnumMode.NULL;
        ObservableCollection<Table.ProductS> customProductSList = new ObservableCollection<Table.ProductS>();

        public void Init()
        {
            InitVar();
            InitData();
            InitEvent();
        }

        private void InitVar()
        {
            this.Background = App.BackgroundBrush;
            this.Foreground = App.ForegroundBrush;
            foreach (UIElement ui in mainGrid.Children)
            {
                Control c = ui as Control;
                if (c != null)
                {
                    if (c.Name == "buttonSaled")
                        continue;

                    c.Background = App.BackgroundBrush;
                    c.Foreground = App.ForegroundBrush;
                }
            }

            productSListInfo1.Background = Brushes.Green;
            productSListInfo1.Foreground = this.Foreground;
            productSListInfo1.ShowBodyContexMenu = false;
            productSListInfo1.ShowAverage = false;
            productSListInfo1.EnableText = string.Empty;
            productSListInfo1.CanUserAddRows = false;
            productSListInfo1.CanSelectProduct = false;
            productSListInfo1.SelectionUnit = DataGridSelectionUnit.FullRow;
            productSListInfo1.ProductSType = ProductS.GetProductS.EnumProductS.可销售商品;
            productSListInfo1.Init(DoubleHConfig.UserConfig.GetUserUIparams(DataTableText.Pos零售商品编辑触摸屏));

            uCPagePanel1.Init(DoubleHConfig.UserConfig.GetUserUIparams(DataTableText.Pos零售商品编辑触摸屏));
            uCPagePanel1.Background = this.Background;
            uCPagePanel1.Foreground = this.Foreground;
            uCPagePanel1.FontSize = DoubleHConfig.AppConfig.PosProductFontSize;
            switch (DoubleHConfig.AppConfig.PosProductShowMode)
            {
                case 1: uCPagePanel1.ListViewBodyTempleteName = DoubleH.Utility.UC.PagePanel.PageListView.EnumModeTemplete.PosProductSItemTemplateNoText; break;
                case 2: uCPagePanel1.ListViewBodyTempleteName = DoubleH.Utility.UC.PagePanel.PageListView.EnumModeTemplete.PosProductSItemTemplateNoImg; break;
            }


            labelCashboxMoney.Content = DoubleHConfig.AppConfig.PosCashboxMoney;
            buttonGuaDan.IsEnabled = Table.UserS.LoginUser.GetAuthority(Table.PosS.EnumAuthority.挂单) != Table.UserS.EnumAuthority.无权限;
            buttonConfig.IsEnabled = Table.UserS.LoginUser.GetAuthority(Table.PosS.EnumAuthority.POS机配置) != Table.UserS.EnumAuthority.无权限;
            buttonTuiHuo.IsEnabled = Table.UserS.LoginUser.GetAuthority(Table.PosS.EnumAuthority.退货) != Table.UserS.EnumAuthority.无权限;
        }

        private void InitEvent()
        {
            productSListInfo1.MouseDoubleClick += (ss, ee) => productSListInfo1.RemoveSelectedItem();
            uCPagePanel1.ItemDoubleClick += (ee) => AddProductSToSale(ee);
            buttonSaled.Click += (ss, ee) => SaleToPay();

            buttonQuantity.Click += (ss, ee) => SelectMode(buttonQuantity);
            buttonPrice.Click += (ss, ee) => SelectMode(buttonPrice);
            buttonVIP.Click += (ss, ee) => SelectMode(buttonVIP);
            buttonOK.Click += (ss, ee) => ButtonOKClick();
            button0.Click += (ss, ee) => textBoxInput.AppendText("0");
            button1.Click += (ss, ee) => textBoxInput.AppendText("1");
            button2.Click += (ss, ee) => textBoxInput.AppendText("2");
            button3.Click += (ss, ee) => textBoxInput.AppendText("3");
            button4.Click += (ss, ee) => textBoxInput.AppendText("4");
            button5.Click += (ss, ee) => textBoxInput.AppendText("5");
            button6.Click += (ss, ee) => textBoxInput.AppendText("6");
            button7.Click += (ss, ee) => textBoxInput.AppendText("7");
            button8.Click += (ss, ee) => textBoxInput.AppendText("8");
            button9.Click += (ss, ee) => textBoxInput.AppendText("9");
            buttonDote.Click += (ss, ee) => textBoxInput.AppendText(".");
            buttonDelete.Click += (ss, ee) => textBoxInput.Clear();

            buttonGuaDan.Click += (ss, ee) => GuaDan();
            buttonNew.Click += (ss, ee) => NewOrder(Table.PosOrderS.EnumFlag.POS零售单);
            buttonJiaoBan.Click += (ss, ee) => JiaoBanNow();
            buttonConfig.Click += (ss, ee) => App.SysConfig();
            buttonTuiHuo.Click += (ss, ee) => App.TuiHuo();
            buttonClose.Click += (ss, ee) => App.Close();
            buttonLogoff.Click += (ss, ee) => App.LogOff(true);
        }

        private void InitData()
        {
            uCPagePanel1.LoadData(Table.GroupS.GetList(Table.GroupS.EnumFlag.商品分类, Table.GroupS.EnumEnable.启用), Table.ProductS.GetListForPos(string.Empty));
            if (DoubleHConfig.AppConfig.PosProductSMode == 0)
            {
                if (!string.IsNullOrEmpty(DoubleHConfig.AppConfig.PosCustomProductS))
                {
                    List<Int64> id = new List<long>();
                    foreach (string str in DoubleHConfig.AppConfig.PosCustomProductS.Split(','))
                        id.Add(Int64.Parse(str));

                    customProductSList = Table.ProductS.GetList(id.ToArray()) ?? new ObservableCollection<Table.ProductS>();
                }
                uCPagePanel1.HomeData=customProductSList;
            }
            else
            {
                customProductSList = Table.ProductS.GetListForPos(DoubleHConfig.AppConfig.PosProductSCount);
                uCPagePanel1.HomeData=customProductSList;
            }
        }

        private void SelectMode(Button btn)
        {
            btn.IsEnabled = false;
            mode = (EnumMode)Enum.Parse(typeof(EnumMode), btn.Content.ToString());
        }

        private void SaleToPay()
        {
            if (!productSListInfo1.HasItems)
                return;

            Clear();
            if (Saled != null)
                Saled();
        }

        private void ButtonOKClick()
        {
            switch (mode)
            {
                case EnumMode.会员: ChangeVipNO(); break;
                case EnumMode.价格:
                    if (Table.UserS.LoginUser.GetAuthority(Table.PosS.EnumAuthority.更改零售价) == Table.UserS.EnumAuthority.无权限)
                    {
                        MessageWindow.Show("权限不足");
                        break;
                    }

                    Table.ProductS ps1 = productSListInfo1.SelectedItem as Table.ProductS;
                    if (ps1 == null)
                        break;

                    double d1 = 0;
                    if (double.TryParse(textBoxInput.Text, out d1))
                        ps1._TempPrice = d1;

                    break;

                case EnumMode.数量:
                    Table.ProductS ps2 = productSListInfo1.SelectedItem as Table.ProductS;
                    if (ps2 == null)
                        break;

                    double d2 = 0;
                    if (double.TryParse(textBoxInput.Text, out d2))
                        ps2._TempQuantity = d2;

                    break;

                default:
                    if (string.IsNullOrEmpty(textBoxInput.Text))
                        break;

                    Table.ProductS product = MainWindow.GetProductSBySearch(textBoxInput.Text.Trim());
                    if (product == null)
                        MessageWindow.Show("商品不存在");
                    else
                    {
                        productSListInfo1.InsertItem(0, product);
                        productSListInfo1.SelectedIndex = 0;
                    }
                    if (productSListInfo1.Count > 0)
                        productSListInfo1.SelectedIndex = 0;
                    break;
            }
            Clear();
        }

        private void Clear()
        {
            mode = EnumMode.NULL;
            buttonQuantity.IsEnabled = true;
            buttonPrice.IsEnabled = true;
            buttonVIP.IsEnabled = true;
            textBoxInput.Clear();
        }

        private void AddProductSToSale(object ee)
        {
            Table.ProductS product = ee as Table.ProductS;
            Debug.Assert(product != null);

            product.InitPrice(null);
            productSListInfo1.InsertItem(0, product);
            productSListInfo1.SelectedIndex = 0;

            if (productSListInfo1.Count > 0)
                productSListInfo1.SelectedIndex = 0;
        }

        private void ChangeVipNO()
        {
            if (string.IsNullOrEmpty(textBoxInput.Text))
            {
                productSListInfo1.CorS = null;
                labelRemainIntegral.Content = null;
                labelVipNO.Content = null;
                return;
            }

            Table.CorS vip = Table.CorS.GetVipObject(textBoxInput.Text);
            textBoxInput.Clear();
            if (vip == null || vip.Id == -1)
            {
                MessageWindow.Show("会员不存在");
                return;
            }
            if (vip.VipDateEnd < DateTime.Now)
            {
                MessageWindow.Show("会员已过期");
                return;
            }
            //如果此会员已经有挂单了，就直接调取出来
            ClassGuaDan gd = App.GuaDanList.FirstOrDefault<ClassGuaDan>(c => c.CorSId == vip.Id);
            if (gd != null)
                ReadGuaDan(gd);
            else
            {
                labelVipNO.Content = vip.VipNO;
                labelRemainIntegral.Content = vip.VipRemainIntegral;
                App.Order.CorSId = vip.Id;
                productSListInfo1.CorS = vip;
            }
        }

        public void ReadGuaDan(ClassGuaDan gd)
        {
            if (gd == null)
                return;

            App.Order = gd.ToOrder();
            productSListInfo1.ItemsSource = App.Order.ProductSList;
            labelVipNO.Content = gd.VipNO;
            labelRemainIntegral.Content = gd.RemainIntegral;
            App.GuaDanList.Remove(gd);
        }


        //接口
        private void JiaoBanNow()
        {
            if (JiaoBan != null)
                JiaoBan();
        }

        public void GuaDan()
        {
            if (!string.IsNullOrEmpty(textBoxInput.Text))//取单
            {
                int i = 0;
                if (int.TryParse(textBoxInput.Text, out i))
                {
                    if (i > 0 && i <= App.GuaDanList.Count)
                        ReadGuaDan(App.GuaDanList[i - 1]);
                }

                return;
            }

            //商品都没有，有必要挂单吗？
            if (!productSListInfo1.HasItems)
                return;

            MessageWindow.Show("已挂单");
        }

        public Int64 CorSId { get { return App.Order.CorSId; } }

        public Table.StoreS StoreS { set { productSListInfo1.StoreS = value; } }

        public string VipNO { get { return labelVipNO.Content.ToString(); } }

        public string RemainIntegral { get { return labelRemainIntegral.Content.ToString(); } }

        public void NewOrder(Table.PosOrderS.EnumFlag flag)
        {
            if (App.Order != null)
            {
                labelVipNO.Content = "无";
                labelRemainIntegral.Content = string.Empty;
                labelCashboxMoney.Content = DoubleHConfig.AppConfig.PosCashboxMoney;
            }
            App.Order = new Table.PosOrderS(flag);
            productSListInfo1.ItemsSource = App.Order.ProductSList;
            productSListInfo1.CorS = null;
        }
    }
}